import axios from 'axios'
import store from '@/store/store.js'
import Vue from 'vue'
import { Notify } from 'vant'
import ElementUI from 'element-ui'

Vue.use(Notify)
// 创建axios实例
const service=axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 30000, // 请求超时时间
  headers:{
    'Content-type': 'application/json',
  }
})

//异步请求前在header里加入token
service.interceptors.request.use(
  config => {
    // console.log("拦截器起作用")
    if(config.url === 'user/register' || config.url === 'user/login'){
      //如果是登录和注册操作，则不需要携带header里面的token
      // console.log("这是不需要在header加token的")
    }else{
      // console.log("这是需要在header加token的")
      if (localStorage.getItem('Authorization')) {
        config.headers.Authorization = localStorage.getItem('Authorization');
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });


// 响应拦截器
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          error.message = '未授权，请登录'
            // 删除本地的token
            localStorage.removeItem('Authorization');
            // 重新回到登陆页面
            this.$router.push('/login');
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
      Notify(error.message)
    }
    return Promise.reject(error)
  }
)
export default service
